package com.dayu.tcp.listener;

import com.dayu.tcp.exception.SocketRuntimeException;
import com.dayu.tcp.future.InvokeFuture;
import com.dayu.tcp.logging.Log;
import com.dayu.tcp.logging.LogFactory;
import com.dayu.tcp.protocol.K1HeartbeatMsg;
import com.dayu.tcp.protocol.K1RestfulRequest;
import com.dayu.tcp.protocol.K1RestfulResponse;
import com.dayu.tcp.service.WrappedChannel;
import io.netty.channel.ChannelHandlerContext;

/**
 * @author yehangtech
 * @date 2024/3/29
 * @description 大禹TCP前置的消息事件处理, 会向下传递
 */
public class BeforeMessageEventListener implements MessageEventListener {

    private static final Log log = LogFactory.getLog(BeforeMessageEventListener.class);

    @Override
    public EventBehavior channelRead(ChannelHandlerContext ctx, WrappedChannel channel, Object msg) {
        if (log.isDebugEnabled()) {
            log.debug("Message received on channel [" + channel.id().asShortText() + "]");
        }
        if (null != msg) {
            if (msg instanceof K1RestfulRequest) {
                K1RestfulRequest k1RestfulRequest = (K1RestfulRequest) msg;
                processK1RestfulRequest(k1RestfulRequest, channel);
            } else if (msg instanceof K1RestfulResponse) {
                K1RestfulResponse k1RestfulResponse = (K1RestfulResponse) msg;
                processK1RestfulResponse(k1RestfulResponse, channel);
            } else if (msg instanceof K1HeartbeatMsg) {
                //收到的是心跳信息没必须要向下传递
                ctx.writeAndFlush(msg);
                return EventBehavior.BREAK;
            }
        }

        return EventBehavior.CONTINUE;
    }

    /**
     * 处理K1RestfulRequest
     *
     * @param k1RestfulRequest
     * @param channel
     */
    private void processK1RestfulRequest(K1RestfulRequest k1RestfulRequest, WrappedChannel channel) {
        //忽略
    }

    /**
     * 处理K1RestfulResponse
     *
     * @param k1RestfulResponse
     * @param channel
     */
    private void processK1RestfulResponse(K1RestfulResponse k1RestfulResponse, WrappedChannel channel) {
        InvokeFuture invokeFuture = channel.getFutureMap().remove(k1RestfulResponse.getSequence());
        if (null != invokeFuture) {
//            if (k1RestfulResponse.getErrNo() != 0) {
//                invokeFuture.setCause(new SocketRuntimeException(k1RestfulResponse.getErrInfo()));
//            } else {
//                invokeFuture.setResult(k1RestfulResponse);
//            }
            invokeFuture.setResult(k1RestfulResponse);
        }
    }
}
